<!--
/**
* Author: gqz
* Date: 2021-07-28 18:01
* Desc: ZmImage
*/
-->
<template>
  <view
    :style="pattern"
    class="zm-image"
    :class="customClass"
    @click="handleClick"
  >
    <u--image
      v-if="visible"
      :src="currentUrl"
      :radius="radius"
      :mode="mode"
      :fade="fade"
      :border-radius="borderRadius"
      width="100%"
      height="100%"
      :lazy-load="lazyLoad"
      :shape="shape"
      @load="handleLoad"
      @error="handleError"
    >
      <view slot="loading"></view>
      <view slot="error"></view>
    </u--image>
  </view>
</template>

<script lang="ts">
  import styleMixins from '@/mixins/styleMixins'
  import { Component, Prop, Mixins, Emit, Watch } from 'vue-property-decorator'
  import config from '@/config'
  import { getObjectUrl, isCosUrl } from '@/utils/cos/cosUpload'
  @Component({
    name: 'ZmImage'
  })
  export default class ZmImage extends Mixins(styleMixins) {
    @Prop({ type: String, default: 'aspectFill' }) readonly mode!: string
    @Prop({ type: String, default: '' }) readonly width!: string
    @Prop({ type: String, default: '' }) readonly height!: string
    @Prop({ type: String, default: '' }) readonly shape!: string
    @Prop({ type: [String, Number], default: '' }) readonly radius!: string
    @Prop({ type: String }) readonly src!: string //图片地址
    @Prop({ type: Boolean, default: false }) readonly isJoin!: boolean
    @Prop({ type: Boolean, default: true }) readonly lazyLoad!: boolean
    @Prop({ type: Boolean, default: false }) readonly fade!: boolean
    @Prop({ type: [String, Number], default: 0 }) borderRadius!: string | number
    @Emit('click')
    handleClick(e) {
      return e
    }

    cosUrl = ''

    get currentUrl() {
      if (this.isJoin) {
        return config.ossUrl + this.src
      } else {
        return isCosUrl(this.src) ? this.cosUrl : this.src
      }
    }
    get pattern() {
      if (this.width || this.height) {
        return `width:${this.width};height:${this.height};${this.customStyle}`
      } else {
        return this.customStyle
      }
    }
    @Watch('src', { immediate: true, deep: true })
    srcChange(val = '') {
      if (isCosUrl(val)) {
        getObjectUrl(val).then((res) => {
          this.cosUrl = res
        })
      }
    }

    resetNum = 1
    handleError() {
      if (isCosUrl(this.src)) {
        if (this.resetNum <= 5) {
          setTimeout(() => {
            this.resetNum = this.resetNum + 1
            this.reRender()
          }, 2000)
        }
      }
    }
    handleLoad() {
      this.$emit('load', true)
    }
    visible = true
    reRender() {
      this.visible = false
      this.$nextTick(() => {
        this.visible = true
      })
    }
  }
</script>
<style lang="scss" scoped>
  .zm-image {
    /deep/ image {
      display: block;
    }
  }
</style>
